<template>
  <el-card>
    <template #header>
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="'/layout'">首页</el-breadcrumb-item>
        <el-breadcrumb-item>内容管理</el-breadcrumb-item>
      </el-breadcrumb>
    </template>
    <el-form label-width="100px" :model="form" :rules="rules" ref="form">
      {{ form }}
      <el-form-item label="标题:" prop="title">
        <el-input placeholder="请输入文章标题" v-model="form.title"></el-input>
      </el-form-item>
      <el-form-item label="频道:" prop="channel_id">
        <!-- {{ form.channel_id }} -->
        <HmSelect :form="form"></HmSelect>
      </el-form-item>
      <el-form-item label="封面:" prop="cover">
        <el-radio-group v-model="form.cover.type" @change="radioChange">
          <el-radio :label="1">单图</el-radio>
          <el-radio :label="3">三图</el-radio>
          <el-radio :label="0">无图</el-radio>
          <el-radio :label="-1">自动图</el-radio>
        </el-radio-group>
        <div v-if="bool">
          <el-upload
            :file-list="fileList"
            name="image"
            list-type="picture-card"
            :action="baseUrl + '/v1_0/upload'"
            :limit="form.cover.type"
            :on-success="onSuccess"
            :on-remove="onRemove"
            :before-upload="beforeUpload"
            v-if="form.cover.type > 0"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </div>
      </el-form-item>
      <el-form-item label="内容:" prop="content">
        <quillEditor
          v-model="form.content"
          @change="editorChange"
        ></quillEditor>
      </el-form-item>
      <el-form-item>
        <div v-if="!$route.query.id">
          <el-button type="primary" @click="submit(false)">发布文章</el-button>
          <el-button @click="submit(true)">存为草稿</el-button>
        </div>
        <div v-else>
          <el-button type="primary" @click="edit(false)">编辑文章</el-button>
          <el-button @click="edit(true)">存为草稿</el-button>
        </div>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
import { mpArticlesPost, mpArticlesGet, mpArticlesPut } from '@/api/index.js'
export default {
  components: {
    quillEditor
  },
  data () {
    return {
      baseUrl: process.env.VUE_APP_URL,
      bool: true,
      form: {
        title: '', // string必须 文章标题
        channel_id: '', // number必须 文章所属频道id
        cover: {
          type: 1, // string必须封面类型 -1:自动，0-无图，1-1张，3-3张
          images: [] // string必须 item 类型: string
        }, // object必须
        content: '' // string必须 文章内容
      },
      rules: {
        title: [{ required: true, message: '必填', trigger: 'change' }],
        channel_id: [{ required: true, message: '必填', trigger: 'change' }],
        cover: [
          { required: true, message: '必填', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              if (value.type > 0) {
                value.images.length === value.type
                  ? callback()
                  : callback(new Error(`请上传${value.type}张图片`))
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ],
        content: [{ required: true, message: '必填', trigger: 'change' }]
      }
    }
  },
  async created () {
    if (this.$route.query.id) {
      const res = await mpArticlesGet(this.$route.query.id)
      console.log('指定id获取res:', res)
      this.form = res.data
    }
  },
  computed: {
    // 计算属性 依赖一个
    fileList () {
      return this.form.cover.images.map(item => {
        return { url: item }
      })
    }
  },
  methods: {
    // 单选框改变
    radioChange () {
      this.form.cover.images = []
      this.bool = false
      this.$nextTick(() => {
        this.bool = true
      })
    },

    // 图片上传成功
    onSuccess (res) {
      console.log('上传成功res:', res)
      this.form.cover.images.push(res.data.url)
      // 上传成功后局部验证图片1.3
      this.$refs.form.validateField(['cover'], () => {})
    },

    // 图片删除成功
    onRemove (file) {
      console.log('删除成功file:', file)
      const _index = this.form.cover.images.findIndex(item => item === file.url)
      this.form.cover.images.splice(_index, 1)
    },

    // 图片上传之前得处理
    beforeUpload (file) {
      console.log('上传之前file:', file)
      const isImage = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLimit2M = file.size / 1024 / 1024 < 2
      if (!isImage) {
        this.$message.error('图片格式只能为png或jpg')
      }
      if (!isLimit2M) {
        this.$$message.error('请上传小于2M的图片')
      }
      return isImage && isLimit2M
    },

    // 发布文章/存为草稿
    submit (bool) {
      // 全局验证表单1.1
      this.$refs.form.validate(async result => {
        if (result) {
          await mpArticlesPost(this.form, bool)
          // console.log('发表文章res:', res)
          this.$message.success(bool ? '存为草稿成功' : '文章发表成功')
          this.$router.push('/layout/article')
        }
      })
    },

    // 富文本局部验证 不是ele自带组件不会自动触发验证,自带有change事件
    editorChange () {
      // 局部验证富文本1.2
      this.$refs.form.validateField(['content'], () => {})
    },
    // 编辑文章/存为草稿
    edit (bool) {
      // 全局验证表单1.1
      this.$refs.form.validate(async result => {
        if (result) {
          await mpArticlesPut(this.form, bool)
          // console.log('发表文章res:', res)
          this.$message.success(bool ? '存为草稿成功' : '文章编辑成功')
          this.$router.push('/layout/article')
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
::v-deep .ql-editor {
  min-height: 150px;
}
</style>
